package com.st.emps.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload {

	public static Map<String,Object> upload(HttpServletRequest request) throws FileUploadException,UnsupportedEncodingException,IOException{
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		Map<String,Object> map = new HashMap<String, Object>();
		List<String> filenames = new ArrayList<String>();
		for(FileItem item :items) {
			if(item.isFormField()) {
				String value = item.getString();
					value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
					map.put(item.getFieldName(), value);
			}else {
				System.out.println(item.getFieldName()+"\t"+item.getName());
				String fn = getFName(item);
				FileOutputStream fw = new FileOutputStream(getFPath()+"/"+fn);
				byte[] b = new byte[1024*1024];
				int length = -1;
				InputStream is = item.getInputStream();
				while(-1 != (length = is.read(b)))
					fw.write(b, 0, length);
				fw.flush();
				fw.close();
				is.close();
				filenames.add(fn);
			}
			
		}
		map.put("list", filenames);
		return map;
	}

	private static File getFPath() {
		File f = new File("D:/DxOffice/workspace/image");
		if(!f.exists())
			f.mkdir();
		return f;
	}

	private static String getFName(FileItem item) {
		String fn = item.getName();
		fn = UUID.randomUUID().toString() + fn.substring(fn.indexOf("."));
		return fn;
	}

	public static void delFile(String filename) {
	File file = new File(getFPath() +"/"+ filename);
    file.delete();
	}
}
